package com.geekhalo.springdata4ddd.order.application;

import com.geekhalo.springdata4ddd.order.model.CreateOrderCommand;
import com.geekhalo.springdata4ddd.order.model.Order;
import com.geekhalo.springdata4ddd.order.model.PaySuccessCommand;
import com.geekhalo.springdata4ddd.order.repository.OrderCommandRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;


/**
 * Created by taoli on 2023/2/4.
 * gitee : https://gitee.com/litao851025/lego
 * 编程就像玩 Lego
 */
@Service
public class OrderApplicationService {
    @Autowired
    private OrderCommandRepository repository;

    @Transactional(readOnly = false)
    public Order createOrder(CreateOrderCommand command){
        // 创建内存对象
        Order order = Order.create(command);
        // 保存到数据库
        this.repository.save(order);
        return order;
    }

    @Transactional(readOnly = false)
    public void modifyAddress(Long orderId, String address){
        Optional<Order> orderOptional = repository.findById(orderId);
        if (orderOptional.isPresent()){
            Order order = orderOptional.get();
            order.modifyAddress(address);
            this.repository.save(order);
        }
    }

    @Transactional(readOnly = false)
    public void paySuccess(PaySuccessCommand command){
        Optional<Order> orderOptional = repository.findById(command.getOrderId());
        if (orderOptional.isPresent()){
            Order order = orderOptional.get();
            order.paySuccess(command);
            this.repository.save(order);
        }
    }
}
